package com.uxsino.commons.baseclass;

import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.uxsino.commons.json.Jsons;

public abstract class AbstractMenu implements ICreateMenu {
    private final Log LOG = LogFactory.getLog(AbstractMenu.class);

    protected abstract String fileClsPath();

    @Override
    public JSONObject create() {
        return JSONObject.parseObject(readFile());
    }

    private String readFile() {
        String fileName = fileClsPath();
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
            if (in == null) {
                LOG.error("【" + fileName + "】菜单文件未找到");
                return null;
            }
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            JsonParser parser = new JsonParser();
            JsonElement ele = parser.parse(reader);
            if (ele.isJsonObject()) {
                return Jsons.of(ele).toJson();
            } else {
                LOG.error("【" + fileName + "】菜单文件不是一个JsonObject");
            }
        } catch (Exception e) {
            LOG.error("【" + fileName + "】菜单文件读取失败");
            return null;
        }
        return null;
    }
}
